<script setup lang="ts">
import { createRentAPI, delEnterpriseAPI, delRentAPI, getEnterpriseListAPI, getRentBuildListAPI, getRentListAPI, outRentAPI } from '@/apis/enterprise';
import type { Datum, Enterprise, EnterpriseListParams, RentBuilding, RentParams } from '@/types/enterprise';
import { ElMessage, ElMessageBox, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';
import type { UploadRequestOptions, UploadRawFile } from 'element-plus';
import { uploadFileAPI } from '@/apis/common';
import router from '@/router';
// 前端自定义的类型，用于展示嵌套表格
interface EnterpriseWithRent extends Enterprise {
  // 合同列表
  rentList: Datum[]
}
// 请求参数
const params = ref<EnterpriseListParams>({
  name: '',
  page: 1,
  pageSize: 5
})
const list = ref<EnterpriseWithRent[]>([])
const total = ref(0)
// 封装获取企业列表函数
const getEnterpriseList = async () => {
  const res = await getEnterpriseListAPI(params.value)
  // console.log(res);
  // map 映射数据用于前端展示
  list.value = res.data.rows.map(item => ({
    ...item,
    rentList: [] // 合同列表默认值，用于嵌套表格渲染
  }))
  total.value = res.data.total
}
getEnterpriseList()

const onSearch = ()=>{
  // 重置页码
  params.value.page = 1
  // 重新获取列表
  getEnterpriseList()
}
// 删除企业
const delEnterprise = async(id: string)=>{
  // 删除属于危险操作，需要二次弹窗确认
  ElMessageBox.confirm(
    '是否删除该企业？', // 内容
    '温馨提示', // 标题
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', // 图标类型
    }
  ).then(async ()=>{
    await delEnterpriseAPI(id)
    ElMessage.success('删除成功')
    // 刷新列表
    getEnterpriseList()
  })
}
// 添加合同业务
const rentDialogVisible = ref(false)// 控制弹窗的显示与隐藏
// 准备表单数据
const rentForm = ref<RentParams>({
  buildingId: undefined,
  startTime: '', 
  endTime: '',
  contractUrl: '',
  contractId: 0,
  type: 0, // 操作类型，添加合同0，续签合同1
  enterpriseId: 0
})
// 表单校验规则
const rentFormRules = ref<FormRules<RentParams>>({
  buildingId: [
    { required: true, message: '请选择楼宇', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择租赁日期', trigger: 'change' }
  ],
  contractId: [
    { required: true, message: '请上传合同文件' }
  ]

})
// 接受下拉框数据
const buildList = ref<RentBuilding[]>([])
// 打开
const addRent = async (id:number)=>{
  rentDialogVisible.value = true
  const res = await getRentBuildListAPI()
  buildList.value = res.data
  // 保存企业id用于添加合同
  rentForm.value.enterpriseId = id
}
// 关闭
const fileList = ref<UploadRawFile[]>([])
const closeDialog = ()=>{
  rentDialogVisible.value = false
  rentFormRef.value?.resetFields()
  // 重置时间数组
    timeArr.value = []
    // 清空文件列表
    fileList.value = []
    // 重置表单数据
    rentForm.value = {
      buildingId: undefined,
      startTime: '',
      endTime: '',
      contractUrl: '',
      contractId: 0,
      type: 0,
      enterpriseId: 0
    }
}
// 时间选择器，监听时间变化
const timeArr = ref<string[]>([])
watch(timeArr, (val) => {
  if (val) {
        rentForm.value.startTime = val[0]
        rentForm.value.endTime = val[1]
      } else {
        rentForm.value.startTime = ''
        rentForm.value.endTime = ''
      }
},{deep: true})
// 通过disabledDate函数 设置禁用掉的日期
const disabledDate = (time: Date) => {
  // 不能小于今日日期，包含今天 （ 1000 * 60 * 60 * 24 -> 1天的毫秒数 ）
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}

// 上传合同文件
const addForm = ref()
const uploadContract = async (options: UploadRequestOptions) => {
  // 1. 把文件处理为 FormData 类型
  const fd = new FormData()
  fd.append('file', options.file)
  fd.append('type', 'contract')

  // 2. 上传文件并保存返回的合同文件 id 和 url 地址
  const res = await uploadFileAPI(fd)
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id

  // 3. 单独校验表单字段
  addForm.value?.validateField('contractId')
}

// 移除合同文件
const removeContract = () => {
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = 0
  // 重新触发验证
  addForm.value?.validateField('contractId')
}

// 文件上传前的验证
const beforeUploadContract = (file: UploadRawFile) => {
  // 验证文件类型
  const validTypes = ['application/pdf', 'application/msword']
  const isValidType = validTypes.includes(file.type)
  
  // 验证文件大小（5MB）
  const isValidSize = file.size / 1024 / 1024 < 5

  if (!isValidType) {
    ElMessage.error('只能上传 PDF 或 DOC 格式的文件!')
  }
  if (!isValidSize) {
    ElMessage.error('文件大小不能超过 5MB!')
  }

  return isValidType && isValidSize
}

// Add form ref
const rentFormRef = ref()

// Update validation in addRentConfirm
const addRentConfirm = async () => {
  try {
    await rentFormRef.value?.validate()
    await createRentAPI(rentForm.value)
    ElMessage.success('添加成功')
    closeDialog()
  } catch {
    // ...
  }
}

// 重置表单
const resetForm = () => {
  rentForm.value = {
    buildingId: undefined,
    startTime: '',
    endTime: '',
    contractUrl: '',
    contractId: 0,
    type: 0,
    enterpriseId: 0
  }
  timeArr.value = []
  rentFormRef.value?.resetFields()
}

// 关闭弹窗时重置表单
const onDialogClose = () => {
  closeDialog()
  resetForm()
}

// 展开行或折叠行时触发
const onExpandChange = async (row: EnterpriseWithRent) => {
  // 获取企业的合同列表
  const res = await getRentListAPI(row.id)
  console.log('当前行被展开', res)
  // 把请求回来的数据，直接保存到当前行的企业信息中
  row.rentList = res.data
}
// 删除合同
const delRent = (sonRow:Datum,fatherRow:EnterpriseWithRent) => {
 ElMessageBox.confirm(
    '是否删除该合同？', // 内容
    '温馨提示', // 标题
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', // 图标类型
    }
  ).then(async ()=>{
    await delRentAPI(sonRow.id)
    fatherRow.rentList = fatherRow.rentList.filter(item => item.id !== sonRow.id)
    ElMessage.success('删除成功')
  }).catch(()=>{})
}
// 退租合同
const outRent = (row:Datum)=>{
  ElMessageBox.confirm(
    '是否退租该合同？', // 内容
    '温馨提示', // 标题
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning', // 图标类型
    }
  ).then(async ()=>{
    await outRentAPI(row.id)
    row.status = 3
    ElMessage.success('退租成功')
    
  }).catch(()=>{})
}
// 续租合同
const renewRent = (row: Datum) => {
  // 打开弹窗
  rentDialogVisible.value = true
  // 获取楼宇列表
  getRentBuildListAPI().then(res => {
    buildList.value = res.data
  })
  // 回显数据
  rentForm.value = {
    buildingId: row.buildingId,
    startTime: row.endTime,
    endTime: '',
    contractUrl: '',
    contractId: 0,
    type: 1,
    enterpriseId: row.enterpriseId!
  }
  // 设置时间选择器的值
  timeArr.value = [row.endTime, '']
}
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input v-model="params.name" @keydown="onSearch()" clearable placeholder="请输入内容" class="search-main" />
      <el-button @click="onSearch()" type="primary">查询</el-button>
    </div>
    <div class="create-container">
      <el-button @click="$router.push('/exterpriseAdd')" type="primary">添加企业</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list"  @expand-change="onExpandChange" row-key="id">
        <!-- type="expand" 显示一个可展开的按钮 -->
  <el-table-column type="expand">
    <template #default="{row}">
      <el-table :data="row.rentList">
        <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
        <el-table-column label="租赁起始时间" prop="startTime" />
        <el-table-column label="合同状态" prop="status" >
          <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
  <template v-slot="{ row }">
    <el-tag v-if="row.status === 0" type="warning">待生效</el-tag>
    <el-tag v-else-if="row.status === 1" type="success">生效中</el-tag>
    <el-tag v-else-if="row.status === 2" type="info">已到期</el-tag>
    <el-tag v-else-if="row.status === 3" type="danger">已退租</el-tag>
  </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
        <template #default="{row:sonRow}">
          <el-button @click="renewRent(sonRow)" size="small" type="primary" link>续租</el-button>
            <el-button @click="outRent(sonRow)" size="small" type="primary" link :disabled="row.status === 3">退租</el-button>
            <el-button @click="delRent(sonRow,row)" size="small" type="primary" link :disabled="row.status !== 3">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作" width="280">
          <template #default="{row}" >
            <el-button @click="addRent(row.id)" size="small" type="primary" link>添加合同</el-button>
            
            <el-button @click="$router.push(`/exterpriseDetail/${row.id}`)" size="small" type="primary" link>查看</el-button>
            <el-button @click="$router.push(`/exterpriseAdd/${row.id}`)" size="small" type="primary" link>编辑</el-button>
            <el-button @click="delEnterprise(row.id)" size="small" type="primary" link>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog 
      title="添加合同" 
      v-model="rentDialogVisible" 
      width="580px" 
      @close="onDialogClose"
    >
      <div class="form-container" title="添加合同">
         <!-- 表单区域 -->
         <el-form ref="rentFormRef" label-position="top" :model="rentForm" :rules="rentFormRules" label-width="80px">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="租赁起止日期" prop="endTime">
            <el-date-picker 
            v-model="timeArr"
            :disabled-date="disabledDate" 
            type="daterange" 
            range-separator="至" 
            start-placeholder="开始日期"
              end-placeholder="结束日期" 
              value-format="YYYY-MM-DD"
               />
          </el-form-item>
          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              :http-request="uploadContract"
              :before-upload="beforeUploadContract"
              :limit="1"
              accept=".doc,.pdf"
              @remove="removeContract"
              v-model:file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.doc .pdf, 文件大小不超过5M</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button size="small" @click="addRentConfirm" type="primary">确 定</el-button>
      </template>
    </el-dialog>
    <div class="page-container">
      <el-pagination 
      :total="total" 
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[2, 5, 10, 20]"
      v-model:current-page="params.page"
      v-model:page-size="params.pageSize"
      @change="getEnterpriseList()"
       />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
  display: flex;
  justify-content: flex-end;
}

.form-container {
  padding: 0px 80px;
}
</style>